package com.jihox.abookpro.adapter;

import java.lang.ref.SoftReference;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jihox.abookpro.AccountDetailActivity;
import com.jihox.abookpro.MyApplication;
import com.jihox.abookpro.R;
import com.jihox.abookpro.dao.OrderDAO;
import com.jihox.abookpro.domain.BookProject;
import com.jihox.abookpro.domain.Order;
import com.jihox.abookpro.domain.OrderListItem;
import com.jihox.abookpro.domain.OrderStatus;
import com.jihox.abookpro.domain.Page;
import com.jihox.abookpro.domain.OrderListItem.OrderItem;
import com.jihox.abookpro.fragment.OrderFragment.OnListDataChangeListener;
import com.jihox.abookpro.helper.UserHelper;
import com.jihox.abookpro.uploader.UploadService;
import com.jihox.abookpro.util.ConfigProperties;
import com.jihox.abookpro.util.DensityUtil;
import com.jihox.abookpro.view.JHProgressDialog;

public class OrdersListAdapter extends BaseAdapter{
	
	private OnListDataChangeListener mListDataChangeListener;
	private static final String SHAREDPREFERENCES_CUSTOMERINFO = "CUSTOMER_TOKEN";
	private static int REQUEST_TIMEOUT = 10*1000;
	private static int SO_TIMEOUT = 10*1000;
	private LayoutInflater inflater;
	private LinkedList<OrderListItem> ordersList;
	//正在上传的订单与进度
	private String uploadingOrder;
	private int uploadingProgress;
	private OrderDAO orderHelper;
	private NativeCoverLoader coverLoader;
	private boolean isEdit;
	private JHProgressDialog pd;
	//异步线程池 
	private ExecutorService mExecutorService = Executors.newFixedThreadPool(5);
	//记录progress列表
	private List<ProgressBar> progressList = new ArrayList<ProgressBar>();
	private UploadService uploadService;
	private HashMap<String, SoftReference<Bitmap>> imageCache = new HashMap<String, SoftReference<Bitmap>>();

	private Context mcontext;
	
	public OrdersListAdapter(Context context, LinkedList<OrderListItem> orders)
	{
		this.inflater = LayoutInflater.from(context);
		this.mcontext = context;
		ordersList = orders;
		orderHelper = new OrderDAO(context);
		coverLoader = new NativeCoverLoader();
		isEdit = false;
	}
	
	public OrdersListAdapter(Context context, LinkedList<OrderListItem> orders, OnListDataChangeListener listDataChangeListener)
	{
		this.inflater = LayoutInflater.from(context);
		this.mcontext = context;
		ordersList = orders;
		orderHelper = new OrderDAO(context);
		coverLoader = new NativeCoverLoader();
		isEdit = false;
		mListDataChangeListener=listDataChangeListener;
	}
	
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return ordersList == null ? 0: ordersList.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int index) {
		// TODO Auto-generated method stub
		return index;
	}

	@Override
	public View getView(int index, View convertView, ViewGroup parentView) {
		// TODO Auto-generated method stub
		Holder holder = null;
		if(convertView == null){
			convertView = inflater.inflate(R.layout.order_listitem, null);
			holder = new Holder();
			
			holder.tvNumber = (TextView) convertView.findViewById(R.id.order_listitem_tvnumber);
			holder.tvName = (TextView) convertView.findViewById(R.id.order_listitem_tvname);
			holder.tvPrice = (TextView) convertView.findViewById(R.id.order_listitem_tvprice);
			holder.tvPayPrice = (TextView) convertView.findViewById(R.id.order_listitem_tvpayPrice);
			holder.btnOperator = (Button) convertView.findViewById(R.id.order_listitem_btnOperation);
			holder.tvStatus = (TextView) convertView.findViewById(R.id.order_listitem_tvstatus);
			holder.tvTotal = (TextView) convertView.findViewById(R.id.order_listitem_tvtotal);
			holder.ivCover = (ImageView) convertView.findViewById(R.id.order_listitem_ivcover);
			holder.rlDetail = (RelativeLayout) convertView.findViewById(R.id.order_listitem_rlInfo);
			holder.ivDelete = (ImageView) convertView.findViewById(R.id.order_listitem_ivdelete);
			holder.ivDelete.setOnClickListener(deleteListener);
			holder.tvCreateTime = (TextView) convertView.findViewById(R.id.order_listitem_tvcreateTime);
			holder.progressBar = (ProgressBar) convertView.findViewById(R.id.order_listitem_progressbar);
			progressList.add(holder.progressBar);
			convertView.setTag(holder);
		}else {
			holder = (Holder)convertView.getTag();
		}
		
		holder.progressBar.setProgress(0);
		String orderId = ordersList.get(index).getOrderId();
		holder.tvNumber.setText(orderId);
		if(ordersList.get(index).getStatus() != null && ordersList.get(index).getStatus().length() >0)
		{
			holder.tvStatus.setText(ordersList.get(index).getStatus());
				holder.btnOperator.setVisibility(View.VISIBLE);
				if(OrderStatus.NOTPAY.getStatus().equals(ordersList.get(index).getStatus())){
					holder.btnOperator.setText(R.string.T_Order_Status_Pay);
					holder.btnOperator.setCompoundDrawables(null, null, null, null);
					holder.btnOperator.setEnabled(true);
				}else if(OrderStatus.NOTUPLOAD.getStatus().equals(ordersList.get(index).getStatus())
						|| inflater.getContext().getResources().getString(R.string.T_Order_Status_Upload_Failed).equals(ordersList.get(index).getStatus())){
					if (!ordersList.get(index).isInUpload() && (uploadService!=null && !uploadService.isOrderUploading(orderId)) ) {
						holder.btnOperator.setText(R.string.X_Upload_Again);
						Drawable leftDraw = inflater.getContext().getResources()
								.getDrawable(R.drawable.upload_color_flag);
						leftDraw.setBounds(0, 0, leftDraw.getMinimumWidth(),
								leftDraw.getMinimumHeight());
						holder.btnOperator.setCompoundDrawablePadding(DensityUtil
								.dip2px(inflater.getContext(), 5));
						holder.btnOperator.setCompoundDrawables(leftDraw, null,
								null, null);
						holder.btnOperator.setEnabled(true);
					} else {
						holder.btnOperator.setEnabled(false);
						if(this.uploadingOrder != null && this.uploadingOrder.equals(ordersList.get(index).getOrderId())){
							holder.btnOperator.setText(R.string.T_Order_Status_Uploading);
							holder.progressBar.setProgress(this.uploadingProgress);
						}else {
							holder.btnOperator.setText(R.string.T_Order_Status_Upload_Wait);
						}
						holder.btnOperator.setCompoundDrawables(null, null, null,
								null);
					}
				}else if(OrderStatus.PRODUCTING.getStatus().equals(ordersList.get(index).getStatus())){
					holder.btnOperator.setText(R.string.X_Buy_Again);
					holder.btnOperator.setCompoundDrawables(null, null, null, null);
					holder.btnOperator.setEnabled(true);
				}else {
					holder.btnOperator.setText(R.string.X_Buy_Again);
					holder.btnOperator.setCompoundDrawables(null, null, null, null);
					holder.btnOperator.setEnabled(true);
				}
				holder.btnOperator.setOnClickListener(operatorListener);
				holder.btnOperator.setTag(index);
		}
		
		float payPrice = ordersList.get(index).getTotalAmount() - ordersList.get(index).getDiscountAmount() ;
		payPrice = payPrice > 0 ? payPrice : 0;
		DecimalFormat decimalFormat=new DecimalFormat("0.00");
		holder.tvPayPrice.setText(decimalFormat.format(payPrice));
		if(ordersList.get(index).getOrderItems() != null && ordersList.get(index).getOrderItems().size() >0)
		{
			OrderItem item = ordersList.get(index).getOrderItems().get(0);
			holder.tvName.setText(item.getProductName());
			holder.tvPrice.setText(decimalFormat.format(item.getPrice()));
			holder.tvTotal.setText("x" + item.getNumber());
			holder.ivCover.setTag(ordersList.get(index).getOrderId());
			holder.ivCover.setImageBitmap(null);
			coverLoader.loadCover(holder.ivCover, ordersList.get(index).getOrderId(),item.getProductId());
		}
		holder.rlDetail.setTag(ordersList.get(index));
		holder.rlDetail.setOnClickListener(itemListener);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		holder.tvCreateTime.setText(df.format(ordersList.get(index).getCreateDate()));
		holder.ivDelete.setTag(index);
		if(isEdit && !OrderStatus.NOTUPLOAD.getStatus().equals(ordersList.get(index).getStatus())){
			holder.ivDelete.setVisibility(View.VISIBLE);
			holder.btnOperator.setEnabled(false);
			holder.rlDetail.setEnabled(false);
		}else 
		{
			holder.ivDelete.setVisibility(View.INVISIBLE);
			holder.btnOperator.setEnabled(true);
			holder.rlDetail.setEnabled(true);
		}
		//设置进度条
		holder.progressBar.setTag(index);
		return convertView;
	}
	
	@Override
	public void notifyDataSetChanged(){
		//this.progressList.clear();
		super.notifyDataSetChanged();
	}
	public class AsyncCoverThread extends Thread {
		private ImageView view;
		private Bitmap bmCover;
		private String orderId;
		private AsyncCoverThread(ImageView view, String orderId, int productId){
			this.view = view;
			this.orderId = orderId;
		}
		private Handler updateViewHandler = new Handler(Looper.getMainLooper()) {
			@Override
			public void handleMessage(Message msg){
				switch(msg.what)
				{
				case 1:
					if(bmCover != null && !bmCover.isRecycled())
					{
						SoftReference<Bitmap> bitmapcache = new SoftReference<Bitmap>(bmCover);
						imageCache.put(orderId + "_cover", bitmapcache);
						//避免出现显示错乱的问题
						if(String.valueOf(view.getTag()).equals(orderId)){
							try{
								view.setImageBitmap(bmCover);
							}catch(Exception e){
								
							}
							
						}
						view.invalidate();
					}
					break;
				default:
					Bitmap no_picture = BitmapFactory.decodeResource(inflater.getContext().getResources(), R.drawable.pictures_no);
					view.setImageBitmap(no_picture);
					break;
				}
			}
		};
		
		@Override
		public void run(){
			//从数据据里获取thumbnail
			Order order = orderHelper.getOrderInfo(orderId);
			if(order == null || order.getThumbnail() == null || order.getThumbnail().isRecycled()){
				updateViewHandler.sendEmptyMessage(2);
			}
			
			if (order != null){
				bmCover = order.getThumbnail();
			}
			
			//bmCover = AccountDetailActivity.createCoverBitmap(inflater.getContext(), productId, thumbnail);
			Message msg = new Message();
			msg.what = 1;
			updateViewHandler.sendMessage(msg);
		}
	};
	
	/**
	 * 异步封面加载器
	 */
	private class NativeCoverLoader {
		private NativeCoverLoader() {
		}
		/**
		 * 
		 * @param view
		 * @param orderId
		 * @param productId 产品的种类
		 */
		public void loadCover(ImageView view, String orderId, int productId){
			Bitmap cover = null;
			if (imageCache.containsKey(orderId + "_cover")){
				SoftReference<Bitmap> bitmapcache_ = imageCache.get(orderId + "_cover");
				cover = bitmapcache_.get();
			}
			
			if(cover != null && !cover.isRecycled())
			{
				if(String.valueOf(view.getTag()).equals(orderId)){
					try{
						view.setImageBitmap(cover);
					}catch(Exception ex){
						AsyncCoverThread loadThread = OrdersListAdapter.this.new AsyncCoverThread(view, orderId, productId);
						mExecutorService.execute(loadThread);
					}
				}
				else {
					view.setImageBitmap(null);
				}
			}else 
			{
				//开启异步加载
				AsyncCoverThread loadThread = OrdersListAdapter.this.new AsyncCoverThread(view, orderId, productId);
				mExecutorService.execute(loadThread);
			}
		}
	}
	
	private OnClickListener itemListener = new OnClickListener(){
		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			Intent intent = new Intent();
			OrderListItem item = (OrderListItem) view.getTag();
			intent.putExtra("orderDetail", item);
			intent.setClass(view.getContext(), AccountDetailActivity.class);
			view.getContext().startActivity(intent);
		}
	};
	
	private OnClickListener deleteListener = new OnClickListener(){
		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			if(view.getTag() != null){
				int index = (Integer) view.getTag();
				showDeleteDialog(index);
			}
		}
	};
	
	/**
	 * 操作按钮的事件
	 */
	private OnClickListener operatorListener = new OnClickListener(){
		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			int index = (Integer) view.getTag();
			OrderListItem item = ordersList.get(index);
			Order localOrder = orderHelper.getOrderInfo(item.getOrderId());
			
			if(localOrder!=null){
				if(OrderStatus.NOTPAY.getStatus().equals(ordersList.get(index).getStatus())){
					Page lostPage = null;
					BookProject bookProject = localOrder.getBookProject();
					if((lostPage = ((MyApplication)view.getContext().getApplicationContext()).checkImageExist(bookProject)) != null){
						//去除丢失文件
						//bookProject.getBook().getPages().remove(lostPage);
						AccountDetailActivity.showLostDialog(view, bookProject,localOrder);
					}else {
						OrderListItem orderItem = ordersList.get(index);
						AccountDetailActivity.goToPayActivity(view, localOrder, orderItem);
					}
				}else if(OrderStatus.NOTUPLOAD.getStatus().equals(ordersList.get(index).getStatus()) 
						|| inflater.getContext().getResources().getString(R.string.T_Order_Status_Upload_Failed).equals(ordersList.get(index).getStatus())){
					
					localOrder.setThumbnail(null);
					uploadService.addUploadTask(localOrder);
					item.setInUpload(true);
					Button btnOperator = (Button) view;
					btnOperator.setEnabled(false);
					btnOperator.setText(R.string.T_Order_Status_Upload_Wait);
					btnOperator.setCompoundDrawables(null, null, null, null);
				}else{
					Page lostPage = null;
					view.setClickable(false);
					BookProject bookProject = localOrder.getBookProject();
					if((lostPage = ((MyApplication)view.getContext().getApplicationContext()).checkImageExist(bookProject)) != null){
						AccountDetailActivity.showLostDialog(view, bookProject,localOrder);
						view.setClickable(true);
					}else {
						//跳转OrderActivity
						AccountDetailActivity.goToOrderActivity(inflater.getContext(), localOrder);
					}
				}
			}else{
				Toast.makeText(mcontext, mcontext.getResources().getText(R.string.T_Order_File_NOT_Found), Toast.LENGTH_SHORT).show();
			}
		}
	};
	public void updateData(LinkedList<OrderListItem> orders)
	{
		this.ordersList = orders;
		this.notifyDataSetChanged();
	}
	
	private class Holder{
		public TextView tvNumber;
		public Button btnOperator; //续传，付款等按钮
		public TextView tvName;
		public TextView tvTotal;
		public TextView tvStatus;
		public TextView tvPrice;
		public TextView tvPayPrice;
		public RelativeLayout rlDetail;
		public ImageView ivCover;
		public ImageView ivDelete;
		public TextView tvCreateTime;
		public ProgressBar progressBar;
	}
	
	//清除缓存
	public void clearCache(){
		orderHelper.closedb();
		//NativeImageLoader.getInstance().clearCache();
	}
	//开启Edit模式
	public void setEdit(boolean edit){
		isEdit = edit;
		notifyDataSetChanged();
	}
	public boolean isEdit(){
		return isEdit;
	}
	
	private void showDeleteDialog(final int index) {

		final Dialog dialog = new Dialog(inflater.getContext(), R.style.JHDialog);
		//设置它的ContentView
		dialog.setContentView(R.layout.dialog_general);
		Button buttonOK = (Button) dialog.findViewById(R.id.dialog_button_ok);
		Button buttonCancel = (Button) dialog.findViewById(R.id.dialog_button_cancel);
		TextView dialogTitle = (TextView) dialog.findViewById(R.id.dialog_title);
		TextView dialogMessage = (TextView) dialog.findViewById(R.id.dialog_message);

		OrderListItem item = ordersList.get(index);
		buttonOK.setBackgroundResource(R.drawable.delete_style);
		buttonCancel.setBackgroundResource(R.drawable.green_style);
		buttonOK.setText(R.string.T_Ok);
		buttonCancel.setText(R.string.T_Cancel);
		dialogTitle.setText(R.string.T_Remind_Text);
		dialogMessage.setText(inflater.getContext().getResources().getString(R.string.T_Delete_Config));

		buttonOK.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				if(ordersList != null && ordersList.size() > index){
					DeleteOrderThread deleteThread = new DeleteOrderThread(index);
					pd = JHProgressDialog.show(inflater.getContext(), null,
							inflater.getContext().getResources().getString(R.string.T_Deleting_From_Server));
					deleteThread.start();
				}
			}
		});
		
		buttonCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		
		dialog.show();
	}
	
	//订单删除线程
	private class DeleteOrderThread extends Thread{
		private int index;
		private String orderId;
		public DeleteOrderThread(int index){
			this.index = index;
			OrderListItem item = ordersList.get(index);
			this.orderId = item.getOrderId();
		}
		private final Handler handler= new Handler(inflater.getContext().getMainLooper()){
			@Override
			public void handleMessage(Message msg) {
				pd.dismiss();
				switch (msg.what) {
				case 1:
					ordersList.remove(index);
					mListDataChangeListener.onListDataChange(ordersList.size());
					notifyDataSetChanged();
					Toast.makeText(inflater.getContext(), inflater.getContext().getText(R.string.T_Delete_Success), Toast.LENGTH_SHORT).show();
					break;
				default:
					Toast.makeText(inflater.getContext(), inflater.getContext().getText(R.string.T_Delete_Fail), Toast.LENGTH_LONG).show();
					break;
				}
			}
		};
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
//			String customerCode = MyApplication.getInstance().getCustomerCode();
			String url = ConfigProperties.getDeleteOrderUrl().replace("{}", orderId);
			SharedPreferences preferencesToken = inflater.getContext().getSharedPreferences(SHAREDPREFERENCES_CUSTOMERINFO, inflater.getContext().MODE_PRIVATE);
			String cstToken = preferencesToken.getString("cstToken", "").toString();
//			url = url + ("".equals(customerCode) || null==customerCode ? "" : "?customerCode=" + customerCode);
			HttpGet httpGet = new HttpGet(url);
			UserHelper helper = new UserHelper();
			httpGet.setHeader("username", helper.getUserName());
			httpGet.setHeader("password", helper.getPassword());
			httpGet.setHeader("cstToken", cstToken);
			try {
				BasicHttpParams httpParams = new BasicHttpParams();  
			    HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);  
			    HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);  
				HttpClient httpclient = new DefaultHttpClient(httpParams);
				HttpResponse httpResponse = httpclient.execute(httpGet);
				String result = EntityUtils.toString(httpResponse.getEntity());
				JSONObject responseJson = new JSONObject(result);
//				Log.i("msg", responseJson.getString("cstToken"));
				Log.i("msg", result.toString());
				if(responseJson.getBoolean("success"))
				{
					handler.sendEmptyMessage(1);
				}
				else {
					handler.sendEmptyMessage(2);
				}
			}catch(Exception ex)
			{
				ex.printStackTrace();
				handler.sendEmptyMessage(2);
			}
		}
		
	};
	
	/**
	 * 更新进度条
	 * @param orderId
	 * @param progress
	 */
	public void updateProgressBar(String orderId, int progress, int status, List<String> waitingOrdersId)
	{
		updateUploadAndWaitOrders(orderId,progress,status,waitingOrdersId);
		//查找当前页面中的bar,并更新
		synchronized(progressList){
			for(ProgressBar bar : progressList)
			{
				if(bar != null)
				{
					//根据获得的orderId来更新UI
					int index = (Integer) bar.getTag();
					String barOrderId = ordersList.get(index).getOrderId();
					if(barOrderId.equals(orderId)){
						 bar.setProgress(progress);
						 RelativeLayout parent = (RelativeLayout) bar.getParent();
						 Button btnOperator = (Button) parent.findViewById(R.id.order_listitem_btnOperation); 
						 btnOperator.setText(R.string.T_Order_Status_Uploading);
						 btnOperator.setCompoundDrawables(null, null, null, null);
						 btnOperator.setEnabled(false);
					}
				}
			}
		}
	};
	
	/**
	 * 更新后台中正在上传的任务与等待上传的任务，以及本地ordersList的状态
	 * @param uploadOrderId 
	 * @param waitingOrdersId
	 * @param status 完成的状态
	 */
	private void updateUploadAndWaitOrders(String uploadOrderId, int progress,int status, List<String> waitingOrdersId){
		this.uploadingOrder = uploadOrderId;
		this.uploadingProgress = progress;

		//记录后台上传的线程
		for(OrderListItem item : ordersList)
		{
			if (waitingOrdersId!=null && waitingOrdersId.contains(item.getOrderId())){
				item.setInUpload(true);
			}
			if(item.getOrderId().equals(uploadOrderId)){
				item.setInUpload(true);
			}
		}
		
		if(status == Order.ORDER_STATUS_UPLOADED || Order.ORDER_STATUS_UPLOAD_FAILED == status)
		{
			for(OrderListItem item : ordersList)
			{
				if(item.getOrderId().equals(uploadOrderId)){
					if (status == Order.ORDER_STATUS_UPLOADED ){
						item.setStatus(inflater.getContext().getResources().getString(R.string.T_Order_Status_Producting));
					}else{
						item.setStatus(inflater.getContext().getResources().getString(R.string.T_Order_Status_Upload_Failed));
					}
					
					item.setInUpload(false);
					this.notifyDataSetChanged();
					break;
				}
			}
		}
	}
	
	/**
	 * 获取绑定的数据
	 */
	public List<OrderListItem> getData(){
		return this.ordersList;
	}
	
	public UploadService getUploadService() {
		return uploadService;
	}

	public void setUploadService(UploadService uploadService) {
		this.uploadService = uploadService;
		this.notifyDataSetChanged();
	}
	
}
